package com.stars.easyms.rest.filter;

import com.stars.easyms.base.http.EasyMsRequestEntity;
import com.stars.easyms.rest.exception.RestDuplicateRequestException;
import com.stars.easyms.rest.handler.EasyMsRequestHandler;
import com.stars.easyms.rest.handler.EasyMsResponseHandler;
import com.stars.easyms.rest.handler.EasyMsRestRequestHandler;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>className: EasyMsRestFilter</p>
 * <p>description: rest过滤器</p>
 *
 * @author guoguifang
 * @version 1.2.2
 * @date 2019/7/19 16:05
 */
public final class EasyMsRestFilter implements Filter {

    private final EasyMsRestRequestHandler easyMsRestRequestHandler;

    private final EasyMsRequestHandler easyMsRequestHandler;

    private final EasyMsResponseHandler easyMsResponseHandler;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        boolean isRest = false;
        EasyMsRequestEntity requestEntity = null;
        try {
            requestEntity = easyMsRequestHandler.parseRequestHeader(httpServletRequest);
            isRest = easyMsRestRequestHandler.filter(httpServletRequest, httpServletResponse,
                    requestEntity, easyMsRestRequestHandler::doExecute);
            if (!isRest) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } catch (RestDuplicateRequestException e) {

            // 如果是RestDuplicateRequestException需要返回异常响应信息
            easyMsResponseHandler.handleResponse(e, httpServletResponse);
        } finally {
            if (!isRest && requestEntity != null) {
                easyMsResponseHandler.handleResponse(requestEntity);
            }
            easyMsRequestHandler.clearRequestSynchronization();
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
        // Intentionally blank
    }

    @Override
    public void destroy() {
        // Intentionally blank
    }

    public EasyMsRestFilter(EasyMsRestRequestHandler easyMsRestRequestHandler, EasyMsRequestHandler easyMsRequestHandler,
                            EasyMsResponseHandler easyMsResponseHandler) {
        this.easyMsRestRequestHandler = easyMsRestRequestHandler;
        this.easyMsRequestHandler = easyMsRequestHandler;
        this.easyMsResponseHandler = easyMsResponseHandler;
    }
}